<template>
  <div class="app-container">
    <el-form v-show="state.showSearch" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="设备编号" prop="machineId">
        <el-input v-model="queryParams.machineId" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="设备名称" prop="machineName">
        <el-input v-model="queryParams.machineName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="广告名称" prop="adName">
        <el-input v-model="queryParams.adName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="广告类型" prop="adType">
        <el-select v-model="queryParams.adType" placeholder="请选择" clearable>
          <el-option
            v-for="dict in device_ad_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option
            v-for="dict in device_ad_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市标签" prop="cityName">
        <el-select
          v-model="queryParams.cityName"
          @change="handleSearch(true)"
          fit-input-width
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in cityNameOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['advert:device:add']"
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="state.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="state.loading" :data="tableList">
      <el-table-column
        label="设备编号"
        align="center"
        prop="machineId"
        min-width="110"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          {{
            Array.isArray(scope.row.machineIds)
              ? scope.row.machineIds.join(' ，')
              : scope.row.machineIds
          }}
        </template>
      </el-table-column>
      <el-table-column label="城市标签" align="center" prop="cityName" show-overflow-tooltip />
      <el-table-column
        label="设备名称"
        align="center"
        prop="machineName"
        min-width="100"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          {{
            Array.isArray(scope.row.machineNames)
              ? scope.row.machineNames.join(' ，')
              : scope.row.machineNames
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="广告位置"
        align="center"
        prop="palyAdPositionName"
        min-width="80"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="广告名称"
        align="center"
        prop="adName"
        min-width="110"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="广告类型" align="center" prop="adType" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="device_ad_type" :value="scope.row.adType" />
        </template>
      </el-table-column>
      <el-table-column label="广告内容" align="center" prop="adUrl" min-width="160">
        <template #default="scope">
          <div v-if="scope.row.adType === 1">
            <el-image
              :src="scope.row.adUrl"
              preview-teleported
              hide-on-click-modal
              style="height: 100px"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[scope.row.adUrl]"
              :initial-index="0"
              fit="cover"
            />
          </div>
          <!-- <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
            <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
          </el-dialog> -->
          <div v-if="scope.row.adType === 2">
            <video
              :src="scope.row.adUrl"
              width="200"
              preload
              :autoplay="false"
              controls
              class="video-box"
            ></video>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        align="center"
        prop="palyBeginTime"
        min-width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="结束时间"
        align="center"
        prop="playEndTime"
        min-width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="状态" align="center" prop="palyStatus" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="device_ad_status" :value="scope.row.palyStatus" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作人"
        align="center"
        prop="updateOper"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作时间"
        align="center"
        prop="updateTime"
        min-width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作" align="center" fixed="right" min-width="110">
        <template #default="scope">
          <el-button
            v-if="scope.row.palyStatus === 1"
            v-hasPermi="['advert:device:push']"
            link
            type="primary"
            @click="handlePlayOrPause(scope.row)"
            >推送</el-button
          >
          <el-button
            v-if="scope.row.palyStatus === 2"
            v-hasPermi="['advert:device:shelf']"
            link
            type="primary"
            @click="handlePlayOrPause(scope.row)"
            >下架</el-button
          >
          <!-- <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button> -->
          <el-button
            v-hasPermi="['advert:device:delete']"
            link
            type="primary"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="state.total > 0"
      :total="state.total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList()"
    />

    <operate ref="operateRef" :operType="state.operType" @updateList="getList()" />
  </div>
</template>

<script setup name="Combo">
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getMachineAdvertList,
  playMachineAdvert,
  pushMachineAdvert,
  pushSingleMachineAdvert,
  deleteMachineAdvert
} from '@/api/advert'
import { reactive } from 'vue'
import operate from './templates/operate.vue'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)

const queryRef = ref(null)
const { proxy } = getCurrentInstance()
const { device_ad_type, device_ad_status } = proxy.useDict('device_ad_type', 'device_ad_status')

const AreaOptions = ref([])
const state = reactive({
  currentId: null,
  actionType: '',
  dialogTitle: '',
  showSearch: true,
  total: 1,
  loading: false,
  operType: '',
  detailId: '',
  data: {}
})
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  machineId: null,
  machineSn: null,
  machineName: null,
  adName: null,
  adType: null,
  status: null,
  cityName: ''
})
const tableList = ref([])

function handleSearch(confirm) {
  !confirm && queryRef.value.resetFields()
  getList(true)
}

async function getList(refresh) {
  state.loading = true
  if (refresh) queryParams.value.pageNum = 1
  try {
    const res = await getMachineAdvertList(queryParams.value)
    tableList.value = res?.rows
    state.total = res.total
  } finally {
    state.loading = false
  }
}

/**table Action */
function handleAdd() {
  state.operType = 'add'
  state.data = {}
  console.log('queryParams.value.cityName', queryParams.value.cityName)
  proxy.$refs['operateRef'].show(queryParams.value.cityName, 'add')
}
function handleEdit(row) {
  state.operType = 'edit'
  proxy.$refs['operateRef'].show(row.cityName, 'edit', row.machineAdId)
}
function handlePlayOrPause(row) {
  const tipText =
    row.palyStatus === 1
      ? '在设备【 ' + row.machineNames.join(' 】，【') + '】 推送'
      : '在设备【' + row.machineNames.join(' 】，【') + ' 】 下架'
  const successText = row.palyStatus === 1 ? '推送' : '下架'
  const playOper = row.palyStatus === 1 ? 1 : 0 //传参 投放-1 下架-0
  ElMessageBox.confirm('确认要' + tipText + ' 该广告吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: false
  })
    .then(() => {
      if (successText === '推送') {
        if (row.machineNames.length === 1) {
          pushSingleMachineAdvert({
            machineAdId: `${row.machineAdId}`,
            machineId: row.machineId
          }).then(() => {
            getList()
            ElMessage.success(successText + '成功')
          })
        } else {
          pushMachineAdvert({ machineAdId: `${row.machineAdId}` }).then(() => {
            getList()
            ElMessage.success(successText + '成功')
          })
        }
      } else {
        playMachineAdvert({ machineAdId: row.machineAdId, palyStatus: playOper }).then(() => {
          getList()
          ElMessage.success(successText + '成功')
        })
      }
    })
    .catch(() => {})
}
function handleDelete(obj) {
  ElMessageBox.confirm('确认要删除这行数据吗?', '系统提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: false
  })
    .then(() => {
      deleteMachineAdvert(obj.machineAdId).then(() => {
        getList()
        ElMessage.success('删除成功')
      })
    })
    .catch(() => {})
}

// const dialogImageUrl = ref('')
// const dialogVisible = ref(false)
// function handlePictureCardPreview(url) {
//   dialogImageUrl.value = url
//   dialogVisible.value = true
// }

/**init */
function init() {
  getList()
}

init()
</script>

<style lang="scss" scoped>
:deep(.el-input-number) {
  width: 100px !important;
}
.form-img {
  height: 100px;
  margin-left: 8px;
  border-radius: 8px;
  cursor: pointer;
}
</style>
